package com.sojson.config.response;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sojson.config.interceptor.interfaces.ResponseBodyInterceptorInterface;
import com.sojson.result.interfaces.BeforeBodyWriteInterface;
import com.sojson.util.servlet.ServletUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 将返回的对象加密拦截器
 * 
 * @author liu
 * @date 2020-10-06
 */
@Slf4j
public class ResponseBodyEncryptionInterceptor implements ResponseBodyInterceptorInterface {

    /**
     * Handler要执行了(过滤器执行结束了),如果被过滤器拦截,就不会执行
     * 拦截处理程序的执行。在HandlerMapping确定适当的处理程序对象之后调用,但在HandlerAdapter调用处理程序之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

        setValRequest(BeforeBodyWriteInterface.RESPONSE_BODY_TYPE_KEY, BeforeBodyWriteInterface.JSON_STRING_ENCRYPTION);

        return ResponseBodyInterceptorInterface.super.preHandle(request, response, handler);
    }

    /**
     * 把值放入到当前的Request里
     * 
     * @param key
     * @param value
     */
    private void setValRequest(String key, Object value) {
        ServletUtil.setValRequest(key, value);
    }

    /**
     * 获取当前拦截器的名字
     */
    @Override
    public String getName() {
        String name = "resuEncry";
        log.info("将返回的对象加密拦截器(ResponseBodyEncryptionInterceptor)注入成功,拦截权限为" + name);
        return name;
    }

}